import path from 'path'
import fs from 'fs'
import { NewProject } from './type'

const handlerFileName: string[] = ['docs/.vitepress/config.mts', 'docs/index.md']

function findTsFileByKey(data, targetKey) {
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    if (item.key === targetKey && item.isLeaf) {
      return item.key
    }
    if (item.children) {
      const result = findTsFileByKey(item.children, targetKey)
      if (result) {
        return result
      }
    }
  }
  return null
}

export function readFile(filePath: string) {
  return new Promise((resolve, reject) => {
    const stat = fs.statSync(filePath)
    if (stat.isDirectory()) {
      resolve({ type: 'directory' })
    }
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        console.error(err)
        reject(err)
      } else {
        resolve({ type: 'file', data: data })
      }
    })
  })
}

export function writeFile(filePath: string, data: string) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, data, 'utf8', (err) => {
      if (err) {
        console.error(err)
        reject(err)
      } else {
        resolve('success')
      }
    })
  })
}

function replaceStringInFile(
  filePath: string,
  strArr: { searchString: string; replacement: string }[]
) {
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(err)
      return
    }
    let updatedData = data
    for (let i = 0; i < strArr.length; i++) {
      const { searchString, replacement } = strArr[i]
      updatedData = updatedData.replaceAll(searchString, replacement)
    }
    fs.writeFile(filePath, updatedData, 'utf8', (err) => {
      if (err) {
        console.error(err)
        return
      }
      console.log(`The file ${filePath} has been updated.`)
    })
  })
}

function deleteFolder(folderPath: string) {
  if (fs.existsSync(folderPath)) {
    fs.readdirSync(folderPath).forEach((file) => {
      const curPath = `${folderPath}/${file}`
      if (fs.lstatSync(curPath).isDirectory()) {
        // 递归删除子文件夹
        deleteFolder(curPath)
      } else {
        // 删除文件
        fs.unlinkSync(curPath)
      }
    })
    // 删除空文件夹
    fs.rmdirSync(folderPath)
    console.log(`成功删除文件夹：${folderPath}`)
  } else {
    console.log(`文件夹不存在：${folderPath}`)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const handlerTemplateFile = (filePath: any, value: NewProject) => {
  return new Promise((resolve, reject) => {
    const rootPath = path.join(path.join(value.path, value.title))
    const byKey = findTsFileByKey(filePath, path.join(rootPath, handlerFileName[0]))
    const strArr = [
      { searchString: 'W-TITLE', replacement: value.title },
      { searchString: 'W-DESC', replacement: value.description },
      { searchString: 'W-BASE', replacement: value.title },
      { searchString: 'W-LOGO', replacement: value.logo },
      { searchString: 'W-FOOT-MSG', replacement: value.footMsg },
      { searchString: 'W-COPYRIGHT', replacement: value.copyright }
    ]
    replaceStringInFile(byKey, strArr)
    const byKey1 = findTsFileByKey(filePath, path.join(rootPath, handlerFileName[1]))
    const strArr1 = [
      { searchString: 'W-TITLE', replacement: value.title },
      { searchString: 'W-DESC', replacement: value.description }
    ]
    replaceStringInFile(byKey1, strArr1)
    deleteFolder(path.join(rootPath, '.git'))
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const { exec } = require('child_process')
    exec(
      `cd ${rootPath} && npm config set registry https://registry.npmmirror.com && npm install`,
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      (err, stdout, _stderr) => {
        if (err) {
          console.error(`执行npm命令时出错： ${err}`)
          reject(err)
        }
        console.log(`npm命令输出： ${stdout}`)
        resolve('success')
      }
    )
  })
}
